package mall.kotlin.com.myapplication;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import mall.kotlin.com.myapplication.android5_0.cardview.CardViewActivity;
import mall.kotlin.com.myapplication.android5_0.notification.NotificationActivity;
import mall.kotlin.com.myapplication.android5_0.recyclerview.DividerItemDecoration;
import mall.kotlin.com.myapplication.android6_0.permission.PermissDisPatcherActivity;
import mall.kotlin.com.myapplication.material_design.MaterialDesignActivity;
import mall.kotlin.com.myapplication.view.CustomActivity;
import mall.kotlin.com.myapplication.view.animator.AnimatorActivity;
import mall.kotlin.com.myapplication.view.dispatch.DisPatchTouchEventActivity;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
    List<String> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);
        EventBus.getDefault().register(this);
        for (int i = 0; i < 20; i++) {
            list.add(i + "");
        }
        RecyclerView recyclerView = findViewById(R.id.recy);
        Button carview = findViewById(R.id.cardview);
        Button notif = findViewById(R.id.notification);
        Button per = findViewById(R.id.permissions);
        Button md = findViewById(R.id.md);
        Button vv = findViewById(R.id.vv);
        Button animator = findViewById(R.id.animator);
        Button dis = findViewById(R.id.dis);
        Button asn = findViewById(R.id.asn);
        Button ok = findViewById(R.id.ohttp);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        //  HomeAdapter homeAdapter = new HomeAdapter(this, list);
        //  recyclerView.setAdapter(homeAdapter);
        //  homeAdapter.setOnItemClickListener(new HomeAdapter.OnItemClickListener() {
        //      @Override
        //      public void onItemClick(View view, int position) {
        //          Toast.makeText(MainActivity.this, "点击了" + position, Toast.LENGTH_SHORT).show();
        //      }
        //
        //      @Override
        //      public void onItemLongClick(View view, final int position) {
        //          new AlertDialog.Builder(MainActivity.this)
        //                  .setTitle("确认删除吗?")
        //                  .setNegativeButton("取消", null)
        //                  .setPositiveButton("确定", new DialogInterface.OnClickListener() {
        //                      @Override
        //                      public void onClick(DialogInterface dialog, int which) {
        //                          homeAdapter.removeData(position);
        //                      }
        //                  }).show();
        //      }
        //  });
        carview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, CardViewActivity.class);
                startActivity(intent);
            }
        });
        notif.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, NotificationActivity.class);
                startActivity(intent);
            }
        });
        //
        per.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, PermissDisPatcherActivity.class);
                startActivity(intent);
            }
        });
        md.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MaterialDesignActivity.class);
                startActivity(intent);
            }
        });
        vv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, CustomActivity.class);
                startActivity(intent);
            }
        });
        animator.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AnimatorActivity.class);
                startActivity(intent);
            }
        });
        dis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, DisPatchTouchEventActivity.class);
                startActivity(intent);
            }
        });
        asn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, DisPatchTouchEventActivity.class);
                startActivity(intent);
            }
        });
        //https://www.baidu.com/?tn=97851118_hao_pg
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //                OkHttpClient okHttpClient = new OkHttpClient.Builder()
                //                        .build();
                //                Request request = new Request.Builder()
                //                        .url("http://www.baidu.com")
                //                        .build();
                //                okHttpClient.newCall(request).enqueue(new Callback() {
                //                    @Override
                //                    public void onFailure(Call call, IOException e) {
                //                        if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
                //                            Log.d("onFailure-->", "Main Thread");
                //                        } else {
                //                            Log.d("onFailure-->", "Not Main Thread");
                //                        }
                //                    }
                //
                //                    @Override
                //                    public void onResponse(Call call, Response response) throws IOException {
                //                        if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
                //                            Log.d("onResponse-->", "Main Thread");
                //                        } else {
                //                            Log.d("onResponse-->", "Not Main Thread");
                //                        }
                //                    }
                //                });
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://www.baidu.com/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                IpService ipService = retrofit.create(IpService.class);
                Call<ResponseBody> map4 = ipService.getMap4();
                map4.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
                            Log.d("onResponse-->", "Main Thread");
                        } else {
                            Log.d("onResponse-->", "Not Main Thread");
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
                            Log.d("ffff-->", "Main Thread");
                        } else {
                            Log.d("ffff-->", "Not Main Thread");
                        }
                    }
                });
            }
        });

        //volley
        //implementation 'com.android.volley:volley:1.0.0'
        String url = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=15850781443";
        //        RequestQueue requestQueue = Volley.newRequestQueue(this);
        //        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        //                new Response.Listener<String>() {
        //                    @Override
        //                    public void onResponse(String response) {
        //
        //                    }
        //                }, new Response.ErrorListener() {
        //            @Override
        //            public void onErrorResponse(VolleyError error) {
        //
        //            }
        //        });
        //        StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url,
        //                new Response.Listener<String>() {
        //                    @Override
        //                    public void onResponse(String response) {
        //
        //                    }
        //                }, new Response.ErrorListener() {
        //            @Override
        //            public void onErrorResponse(VolleyError error) {
        //
        //            }
        //        }) {
        //            @Override
        //            protected Map<String, String> getParams() throws AuthFailureError {
        //                Map<String, String> map = new HashMap<String, String>();
        //                map.put("params1", "value1");
        //                map.put("params2", "value2");
        //                return map;
        //            }
        //        };
        //
        //        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
        //            @Override
        //            public void onResponse(JSONObject response) {
        //
        //            }
        //        }, new Response.ErrorListener() {
        //            @Override
        //            public void onErrorResponse(VolleyError error) {
        //
        //            }
        //        });
        //        requestQueue.add(stringRequest);


        ////////////////////////////////////////////////////////////

        //        //okhttp
        //
        //        // implementation 'com.squareup.okhttp3:okhttp:3.11.0'
        //        // implementation 'com.squareup.okio:okio:2.1.0'
        //        File sdcache = getExternalCacheDir();
        //        int cacheSize = 10 * 1024 * 1024;
        //        OkHttpClient okHttpClient = new OkHttpClient();
        //        final OkHttpClient okHttpClient1 = new OkHttpClient.Builder()
        //                .connectTimeout(1000, TimeUnit.MILLISECONDS)
        //                .writeTimeout(10, TimeUnit.SECONDS)
        //                .readTimeout(10, TimeUnit.SECONDS)
        //                .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))
        //                .build();
        //
        //        //get
        //        final okhttp3.Request request = new okhttp3.Request.Builder()
        //                .url(url)
        //                .build();
        //        new Thread(new Runnable() {
        //            @Override
        //            public void run() {
        //                //异步
        //                okHttpClient1.newCall(request).enqueue(new Callback() {
        //                    @Override
        //                    public void onFailure(Call call, IOException e) {
        //
        //                    }
        //
        //                    @Override
        //                    public void onResponse(Call call, okhttp3.Response response) throws IOException {
        //                        String s = response.body().string();
        //                        Log.i("thread",Thread.currentThread().getName());
        //                    }
        //                });
        //
        //                //同步
        //                try {
        //                    okhttp3.Response execute = okHttpClient1.newCall(request).execute();
        //                    if (execute.isSuccessful()){
        //                        String string = execute.body().string();
        //                    }
        //                } catch (IOException e) {
        //                    e.printStackTrace();
        //                }
        //            }
        //        }).start();
        //
        //
        //        //post
        //        MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain;charset=utf-8");
        //        String str = "AndroidContent";
        ////        Headers headers = new Headers();
        //        RequestBody requestBody=RequestBody.create(MEDIA_TYPE_TEXT,str);
        //        okhttp3.Request requestPost= new Request.Builder()
        //                .url(url)
        //                .header("headerkey1","headervalues1")
        ////                .headers(headers)
        //                .header("headerkey2","headervalues2")
        //                .header("headerkey3","headervalues")
        //                .post(requestBody)
        //                .build();
        //        okHttpClient1.newCall(requestPost);
        //
        //        //retrofit
        //        //com.squareup.retrofit2:retrofit:2.5.0.
        //        // compile 'com.squareup.retrofit2:converter-gson:2.3.0' //返回gson 数据
        //        // compile 'com.squareup.retrofit2:converter-scalars:2.3.0'  //返回string数据
        //        Retrofit retrofit = new Retrofit.Builder()
        //                .baseUrl(url)
        //                .client(okHttpClient1)
        //                .addConverterFactory(GsonConverterFactory.create())
        //                .build();
        //        IpService ipService = retrofit.create(IpService.class);
        //        retrofit2.Call<IpBean> map = ipService.getMap();
        //        try {
        //            ipService.getMap2("heheh").execute();
        //        } catch (IOException e) {
        //            e.printStackTrace();
        //        }
        //        map.enqueue(new retrofit2.Callback<IpBean>() {
        //            @Override
        //            public void onResponse(retrofit2.Call<IpBean> call, Response<IpBean> response) {
        //                Log.i("thread",Thread.currentThread().getName());
        //            }
        //
        //            @Override
        //            public void onFailure(retrofit2.Call<IpBean> call, Throwable t) {
        //
        //            }
        //        });
        //
        //


        //rxjava 1
        // implementation 'io.reactivex:rxjava:1.3.8'
        // implementation 'io.reactivex:rxandroid:1.2.1'

        //观察者 obsevber  subscriber  决定当前时间发生的时候,他要这么处理
       /* Observer<String> observer = new Observer<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {

            }
        };
        Subscriber<String> subscriber = new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {

            }
        };
        Action1<String> onnext = new Action1<String>() {
            @Override
            public void call(String s) {

            }
        };
        Action1<Throwable> onerror = new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {

            }
        };
        Action0 oncomple = new Action0() {
            @Override
            public void call() {

            }
        };

        //被观察者 observable  决定什么时候发生事件,发生怎么样的事件
        //当obserable被订阅时,就会调用call ,进行发送事件
        Observable observable = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                subscriber.onNext("Hello");
                subscriber.onNext("Hi");
                subscriber.onNext("Aloha");
                subscriber.onCompleted();
            }
        });
        Observable observable1 = Observable.just("Hello", "Hi", "Aloha");
        Observable observable2 = Observable.from(new String[]{"Hello", "Hi", "Aloha"});

        //订阅
        observable.subscribe(subscriber);
        observable.subscribe(onnext, onerror, oncomple);

        Observable.from(new String[]{"春天", "夏天", "冬天"})
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {

                    }
                });

        final int drawableRes = 0;
        final ImageView imageView = new ImageView(this);
        Observable.create(new Observable.OnSubscribe<Drawable>() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void call(Subscriber<? super Drawable> subscriber) {
                Drawable drawable = getTheme().getDrawable(drawableRes);
                subscriber.onNext(drawable);
                subscriber.onCompleted();
            }
        })
                .subscribeOn(Schedulers.io())   //产生事件时候,就是obserable create时
                .observeOn(AndroidSchedulers.mainThread())  //事件消费的时候,就是subscriber 处理事件时
                .subscribe(new Subscriber<Drawable>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Drawable drawable) {
                        imageView.setImageDrawable(drawable);
                    }
                });


        Observable.just("imagview.png")
                .map(new Func1<String, Bitmap>() {
                    @Override
                    public Bitmap call(String s) {
                        return getBitmap(s);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Bitmap>() {
                    @Override
                    public void call(Bitmap bitmap) {
                        imageView.setImageBitmap(bitmap);
                    }
                });

        Student[] students = {};
        Observable.from(students)
                .map(new Func1<Student, String>() {
                    @Override
                    public String call(Student student) {
                        return student.getName();
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String s) {
                        Log.i("", s);
                    }
                });

        Observable.from(students)
                .flatMap(new Func1<Student, Observable<Course>>() {
                    @Override
                    public Observable<Course> call(Student student) {
                        return Observable.from(student.getCourse());
                    }
                })
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Course>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Course course) {

                    }
                });*/

        //Rxjava2
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                emitter.onNext("nihao1");
                emitter.onNext("nihao2");
                emitter.onNext("nihao3");
                emitter.onComplete();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    Disposable mDisposable;

                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(String s) {
                        if ("nihao2".equals(s)) {
                            mDisposable.dispose();
                        }
                        Log.i("", s);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {

            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {

                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {

                    }
                });


        Observable.create(new ObservableOnSubscribe<okhttp3.Response>() {
            @Override
            public void subscribe(final ObservableEmitter<okhttp3.Response> emitter) throws Exception {
                OkHttpClient okHttpClient = new OkHttpClient.Builder()
                        .build();
                Request request = new Request.Builder()
                        .url("")
                        .build();
                okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
                    @Override
                    public void onFailure(okhttp3.Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                        emitter.onNext(response);
                    }
                });
            }
        })
                .map(new Function<okhttp3.Response, MyAddress>() {
                    @Override
                    public MyAddress apply(okhttp3.Response response) throws Exception {
                        if (response.isSuccessful()) {
                            return new Gson().fromJson(response.body().toString(), MyAddress.class);
                        }
                        return null;
                    }
                })
                .doOnNext(new Consumer<MyAddress>() {
                    @Override
                    public void accept(MyAddress myAddress) throws Exception {
                        //保存
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MyAddress>() {
                    @Override
                    public void accept(MyAddress myAddress) throws Exception {

                    }


                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {

                    }
                }, new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {

                    }
                });


        Observable<FoodList> cache = Observable.create(new ObservableOnSubscribe<FoodList>() {
            @Override
            public void subscribe(ObservableEmitter<FoodList> emitter) throws Exception {
               /* Log.e(TAG, "create当前线程:" + Thread.currentThread().getName());
                FoodList data = CacheManager.getInstance().getFoodListData();

                // 在操作符 concat 中，只有调用 onComplete 之后才会执行下一个 Observable
                if (data != null) { // 如果缓存数据不为空，则直接读取缓存数据，而不读取网络数据
                    isFromNet = false;
                    Log.e(TAG, "\nsubscribe: 读取缓存数据:");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mRxOperatorsText.append("\nsubscribe: 读取缓存数据:\n");
                        }
                    });

                    emitter.onNext(data);
                } else {
                    isFromNet = true;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mRxOperatorsText.append("\nsubscribe: 读取网络数据:\n");
                        }
                    });
                    Log.e(TAG, "\nsubscribe: 读取网络数据:");
                    emitter.onComplete();
                }*/
            }
        });

        Observable<FoodList> net = Observable.create(new ObservableOnSubscribe<FoodList>() {
            @Override
            public void subscribe(final ObservableEmitter<FoodList> emitter) throws Exception {
                OkHttpClient okHttpClient = new OkHttpClient.Builder()
                        .build();
                Request request = new Request.Builder()
                        .url("")
                        .build();
                okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
                    @Override
                    public void onFailure(okhttp3.Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                        emitter.onNext(new Gson().fromJson(response.body().string(), FoodList.class));
                    }
                });
            }
        });

        Observable
                .concat(cache, net, cache, net)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<FoodList>() {
                               @Override
                               public void accept(FoodList foodList) throws Exception {
                       /* Log.e(TAG, "subscribe 成功:" + Thread.currentThread().getName());
                        if (isFromNet) {
                            mRxOperatorsText.append("accept : 网络获取数据设置缓存: \n");
                            Log.e(TAG, "accept : 网络获取数据设置缓存: \n" + foodList.toString());
                            CacheManager.getInstance().setFoodListData(foodList);
                        }

                        mRxOperatorsText.append("accept: 读取数据成功:" + foodList.toString() + "\n");
                        Log.e(TAG, "accept: 读取数据成功:" + foodList.toString());*/
                               }

                           }
                        , new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                               /* Log.e(TAG, "subscribe 失败:" + Thread.currentThread().getName());
                                Log.e(TAG, "accept: 读取数据失败：" + throwable.getMessage());
                                mRxOperatorsText.append("accept: 读取数据失败：" + throwable.getMessage() + "\n");*/

                            }
                        });

        Flowable.interval(1, TimeUnit.MILLISECONDS)
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long s) throws Exception {

                    }
                });

    }


    private Bitmap getBitmap(String s) {
        return null;
    }
}

